<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input clearable v-model="query.questionText" placeholder="请输入题目关键字" />
        <!-- <el-select clearable v-model="query.typeCode" placeholder="题目类型"
					style="margin-left: 10px; width: 200px">
					<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select> -->
        <el-cascader v-model="query.typeCode" :show-all-levels="false" :props="{
          checkStrictly: true,
        }" placeholder="请选择题目类型" style="width: 700px;" clearable :options="typeOptions" @change="handleTypeChange1" />
        <el-button type="primary" @click="loadQuestions" style="margin-left: 10px">
          查询
        </el-button>
        <el-button type="success" @click="handleAdd" style="margin-left: 10px">
          新增题目
        </el-button>
      </div>

      <!-- 题目列表 -->
      <el-table border :header-cell-style="{ background: '#f5f7fa', color: '#000' }" :data="questionList"
        style="width: 100%; margin-top: 20px" height="calc(100vh - 260px)" @expand-change="handleExpand">
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-detail">
              <div class="detail-section">
                <div class="detail-label">题目类型：</div>
                <div class="detail-content">
                  {{typeOptions.find(t => t.value === row.typeCode)?.label}}
                  <span v-if="row.typeCodeChildren">->
                    {{typeOptions.find(t => t.value === row.typeCode)?.children?.
                      find(t => t.value === row.typeCodeChildren)?.label}}
                  </span>
                </div>
              </div>
              <div class="detail-section">
                <div class="detail-label">来源：</div>
                <div class="detail-content">{{ row.source || '暂无来源' }}</div>
              </div>
              <div class="detail-section">
                <div class="detail-label">选项：</div>
                <div class="detail-content options-content">
                  <div v-for="option in row.options" :key="option.optionLabel" class="option-item-expand">
                    <div class="option-label-expand">
                      <!-- {{ option.optionLabel }}. -->
                      <span v-if="row.questionType == 1 || row.questionType == 2"> {{
                        option.optionLabel }}.</span>
                      <span v-else>
                        <span v-if="option.optionLabel == 'A'">
                          <el-icon :size="20">
                            <circle-check />
                          </el-icon>
                        </span>
                        <span v-else-if="option.optionLabel == 'B'">
                          <el-icon :size="20">
                            <circle-close />
                          </el-icon>
                        </span>
                      </span>
                    </div>
                    <div class="option-text" v-html="option.optionText"></div>
                    <div v-if="option.isCorrect" class="correct-tag">
                      正确答案
                    </div>
                  </div>
                </div>
              </div>
              <div class="detail-section">
                <div class="detail-label">解析：</div>
                <div class="detail-content" v-html="row.analysis || '暂无解析'"></div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="questionText" label="题目内容" min-width="500">
          <template #default="{ row }">
            <div class="question-text">
              <div v-html="row.questionText"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="typeCode" label="题目类型" width="120" align="center">
          <template #default="{ row }">
            {{ getTypeLabel(row.typeCode) }}
            <span v-if="row.typeCodeChildren">->
              {{typeOptions.find(t => t.value === row.typeCode)?.children?.
                find(t => t.value === row.typeCodeChildren)?.label}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" align="center" />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-model:current-page="query.pageNum" v-model:page-size="query.pageSize" :total="total"
        @current-change="loadQuestions" @size-change="loadQuestions" layout="->,total, sizes, prev, pager, next"
        style="margin-top: 20px" />

      <!-- 新增/编辑对话框 -->
      <el-drawer v-model="dialogVisible" :title="dialogType === 'add' ? '新增题目' : '编辑题目'" direction="rtl" size="60%"
        :destroy-on-close="true" class="question-drawer">
        <div class="drawer-container">
          <el-form :model="questionForm" :rules="rules" ref="formRef" label-width="100px" class="drawer-form">
            <el-form-item label="题目分类" prop="questionType">
              <!-- 是否是判断题 -->
              <el-checkbox @change="questionTypeChange" false-label="" true-label="99"
                v-model="questionForm.questionType" label="1">判断题</el-checkbox>
            </el-form-item>
            <el-form-item label="知识点" prop="knowledge">
              <el-input v-model="questionForm.knowledge" placeholder="请输入知识点" />
            </el-form-item>
            <el-form-item label="题目类型" prop="typeCode">
              <el-radio-group v-model="questionForm.typeCode" class="radio-group-type">
                <el-radio v-for="item in typeOptions" :key="item.value" :label="item.value" border>
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="子类型" prop="typeCodeChildren" v-if="typeChildrenList.length">
              <el-radio-group v-model="questionForm.typeCodeChildren" class="radio-group-type">
                <el-radio v-for="item in typeChildrenList" :key="item.value" :label="item.value" border>
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干" prop="questionText">
              <wang height="200px" v-model="questionForm.questionText" @change="handleQuestionTextChange" />
            </el-form-item>

            <el-form-item label="选项" prop="options">
              <div class="options-list">
                <div v-for="(option, index) in questionForm.options" :key="index" class="option-row">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <div class="option-editor">
                    <wang v-model="option.optionText" mode="simple" height="100px" />
                  </div>
                  <el-checkbox v-model="correctAnswers" :label="option.optionLabel" @change="handleCorrectChange">
                    正确答案
                  </el-checkbox>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="题目解析" prop="analysis">
              <wang height="200px" v-model="questionForm.analysis" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="drawer-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-drawer>

      <!-- 添加查看详情对话框 -->
      <el-dialog v-model="viewDialogVisible" title="题目详情" width="60%">
        <div class="question-detail">
          <div class="detail-item">
            <label>题目内容：</label>
            <div v-html="viewForm.questionText"></div>
          </div>
          <div class="detail-item">
            <label>题目类型：</label>
            <div>{{typeOptions.find(t => t.value === viewForm.typeCode)?.label}}
              <span v-if="viewForm.typeCodeChildren">->
                {{typeOptions.find(t => t.value === viewForm.typeCode)?.children?.
                  find(t => t.value === viewForm.typeCodeChildren)?.label}}
              </span>
            </div>
          </div>
          <div class="detail-item">
            <label>来源：</label>
            <div>{{ viewForm.source || '暂无来源' }}</div>
          </div>
          <div class="detail-item">
            <label>选项：</label>
            <div style="display: flex" v-for="option in viewForm.options" :key="option.optionLabel" class="option-item">
              <div style="width: 30px">{{ option.optionLabel }}.</div>
              <span v-html="option.optionText"></span>
              <span v-if="option.isCorrect" class="correct-answer">（正确答案）</span>
            </div>
          </div>
          <div class="detail-item">
            <label>解析：</label>
            <div v-html="viewForm.analysis || '暂无解析'"></div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { findAll, delquestion, addquestion } from '../api/timu';
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { typeOptionsList, getTypeLabel, getType } from '../utils/type';
import { t } from '@wangeditor/editor';
// import wang from '../../../plugins/editor-wang/components/wang.vue';

const handleQuestionTextChange = (value: string) => {
  console.log(value);
};

const query = ref({
  pageNum: 1,
  pageSize: 10,
  questionText: '',
  typeCode: ''
});

const typeOptions = ref(typeOptionsList);

const questionList = ref<any>([]);
const total = ref(0);
const dialogVisible = ref(false);
const dialogType = ref('add');
const correctAnswers = ref<any>([]);
const typeChildrenList = ref<any>([])

const questionForm = ref<any>({
  questionText: '',
  typeCode: '',
  options: [
    { optionText: '', isCorrect: false, optionLabel: 'A' },
    { optionText: '', isCorrect: false, optionLabel: 'B' },
    { optionText: '', isCorrect: false, optionLabel: 'C' },
    { optionText: '', isCorrect: false, optionLabel: 'D' }
  ],
  analysis: '',
  knowledge: ''
});
// 题目分类改变
const questionTypeChange = (e) => {
  if (questionForm.value.questionType == 99) {
    questionForm.value.options = [
      { optionText: '正确', isCorrect: true, optionLabel: 'A' },
      { optionText: '错误', isCorrect: false, optionLabel: 'B' },
    ]
    correctAnswers.value.push('A')
  } else {
    questionForm.value.options = [
      { optionText: '', isCorrect: false, optionLabel: 'A' },
      { optionText: '', isCorrect: false, optionLabel: 'B' },
      { optionText: '', isCorrect: false, optionLabel: 'C' },
      { optionText: '', isCorrect: false, optionLabel: 'D' }
    ]
    correctAnswers.value = []
  }
  console.log(questionForm.value.options)
}

const formRef = ref<any>(null);

const rules = {
  questionText: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 2, message: '题目内容至少2个字符', trigger: 'blur' }
  ],
  typeCode: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  options: [
    {
      validator: (rule, value, callback) => {
        // 检查所有选项是否都填写了内容
        const emptyOption = value.find(opt => !opt.optionText.trim());
        if (emptyOption) {
          callback(new Error('请填写所有项内容'));
          return;
        }
        // 检查是否选择了至少一个正确答案
        const hasCorrect = value.some(opt => opt.isCorrect);
        if (!hasCorrect) {
          callback(new Error('请至少选择一个正确答案'));
          return;
        }
        callback();
      },
      trigger: 'change'
    }
  ]
};
const typeCode = ref('')

const handleTypeChange1 = (e) => {
  console.log(e);
  if (e && e.length >= 1) {
    typeCode.value = e.at(-1)
  } else {
    typeCode.value = ''
  }
}

const loadQuestions = async () => {
  try {
    const querys = JSON.parse(JSON.stringify(query.value))
    querys.typeCode = typeCode.value
    const res = await findAll(querys);

    questionList.value = res.data.records.filter(q => q.typeCode != 'data');
    questionList.value.forEach(item => {
      if (item.typeCode && item.typeCode.length > 1) {
        item.typeCodeChildren = item.typeCode
        item.typeCode = item.typeCode.slice(0, 1)
      }
    })
    console.log(questionList.value)
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error('加载题目失败');
  }
};

const handleAdd = () => {
  dialogType.value = 'add';
  questionForm.value = {
    questionText: '',
    typeCode: '',
    typeCodeChildren: '',
    options: [
      { optionText: '', isCorrect: false, optionLabel: 'A' },
      { optionText: '', isCorrect: false, optionLabel: 'B' },
      { optionText: '', isCorrect: false, optionLabel: 'C' },
      { optionText: '', isCorrect: false, optionLabel: 'D' }
    ],
    analysis: '',
    knowledge: ''
  };
  typeChildrenList.value = []
  correctAnswers.value = [];
  dialogVisible.value = true;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleEdit = row => {
  dialogType.value = 'edit';
  questionForm.value = JSON.parse(JSON.stringify(row));
  if (questionForm.value.options) {
    correctAnswers.value = questionForm.value.options
      .filter(opt => opt.isCorrect)
      .map(opt => opt.optionLabel);
  }
  dialogVisible.value = true;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleDelete = row => {
  ElMessageBox.confirm('确认删除该题目吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await delquestion(row.id);
      ElMessage.success('删除成功');
      loadQuestions();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
  });
};

const handleCorrectChange = () => {
  questionForm.value.options.forEach(option => {
    option.isCorrect = correctAnswers.value.includes(option.optionLabel);
  });
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  if (questionForm.value.typeCodeChildren) {
    questionForm.value.typeCode = questionForm.value.typeCodeChildren
  }

  try {
    await formRef.value.validate();
    await addquestion(questionForm.value);
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
    dialogVisible.value = false;
    loadQuestions();
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
    }
  }
};

const viewDialogVisible = ref(false);
const viewForm = ref<any>({
  questionText: '',
  typeCode: '',
  options: [],
  analysis: '',
  source: '',
  knowledge: ''
});

const handleView = row => {
  viewForm.value = JSON.parse(JSON.stringify(row));
  viewDialogVisible.value = true;
};

const handleExpand = (row, expandedRows) => {
  console.log('expanded', row, expandedRows);
};

onMounted(() => {
  loadQuestions();
});
// 题目类型改变

const handleTypeChange = (val) => {
  const typeList: any = getType(val)
  console.log(typeList)
  typeChildrenList.value = []
  if (typeList.children) {
    typeChildrenList.value = typeList.children
  }
}

watch(() => questionForm.value.typeCode, (val) => {
  if (val) {
    handleTypeChange(val)
  }
}, { immediate: true, deep: true })


</script>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.option-row {
  display: flex;
  align-items: center;

  .option-label {
    width: 30px;
    margin-right: 10px;
  }

  .el-radio {
    margin-left: 20px;
  }
}

.question-detail {
  padding: 20px;

  .detail-item {
    margin-bottom: 24px;

    label {
      font-weight: bold;
      margin-bottom: 12px;
      display: block;
      color: #606266;
    }

    div {
      line-height: 1.6;
      color: #303133;
    }
  }

  .option-item {
    margin: 12px 0;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border-radius: 4px;

    .correct-answer {
      color: #67c23a;
      margin-left: 12px;
      font-weight: 500;
    }
  }
}

.question-text {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.8;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;

  // 调整滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: #f5f5f5;
  }

  // 调整题目内容样式
  ::v-deep(p) {
    margin: 0;
    color: #303133;
  }

  ::v-deep(img) {
    max-width: 100%;
    height: auto;
    margin: 8px 0;
  }
}

.option-editor {
  flex: 1;
  margin-right: 20px;
  max-width: 700px;
}

.expand-detail {
  padding: 20px 50px;
  background-color: #deedfb;

  .detail-section {
    display: flex;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-label {
      width: 80px;
      color: #606266;
      font-weight: 500;
    }

    .detail-content {
      flex: 1;
      color: #303133;

      &.options-content {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }
    }
  }
}

.option-item-expand {
  display: flex;
  align-items: flex-start;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;

  .option-label-expand {
    width: 30px;
    color: #606266;
  }

  .option-text {
    flex: 1;
    margin: 0 12px;
  }

  .correct-tag {
    padding: 2px 8px;
    background-color: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 12px;
  }
}

.radio-group-type {
  :deep(.el-radio) {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

.drawer-form {
  padding: 20px;
}

.question-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0;
    height: calc(100% - 120px); // 减去header和footer的高度
    overflow: hidden;
  }
}

.drawer-container {
  height: 100%;
  overflow-y: auto;
  padding: 20px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }
}

.drawer-form {
  .el-form-item {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  text-align: right;

  .el-button {
    margin-left: 12px;
  }
}

.option-row {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }

  .option-editor {
    margin: 12px 0;
  }
}

.radio-group-type {
  :deep(.el-radio) {
    margin-right: 15px;
    margin-bottom: 10px;

    &.is-bordered {
      padding: 8px 15px;
    }
  }
}
</style>
